package edu.cmich.cps.cps240.partyprincesspalace.hw06;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JRadioButton;

/**
 * Custom button which tells the workspace when the user
 * has selected a chip to add
 * @author holde1ja
 */
public class ChipButton extends JRadioButton {
	private static final long serialVersionUID = 7708528809740214300L;
	private Chip chip;
	private Workspace workspace;
	
	/**
	 * Intializes the chip button
	 * @param p_chip The chip that we will be creating copies of in the workspace
	 * @param p_workspace A handle to the workspace
	 */
	public ChipButton(Chip p_chip, Workspace p_workspace)
	{
		this.setIcon(generateIcon(p_chip));
		this.setSelectedIcon(this.getIcon());
		this.setPressedIcon(this.getIcon());
		workspace = p_workspace;
		chip = p_chip;
		this.setPreferredSize(new Dimension(chip.getRectangle().width, 
				chip.getRectangle().height));
		
		this.addActionListener( new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (e.getSource() instanceof ChipButton)
				{
					((ChipButton)e.getSource()).processClickEvent();
				}
			}});
	}
	
	/**
	 * Generates an icon for the chip based off of the chip's name and size
	 * @param chip the chip that we will be generating an icon for
	 * @return A new icon to represent the given chip
	 */
	private static Icon generateIcon(Chip chip)
	{
		//Created a buffered image, grabs a graphics context for it
		//and draws the chip directly into the buffered image's graphics context
		BufferedImage img = new BufferedImage(chip.getRectangle().width,
				chip.getRectangle().width, BufferedImage.TYPE_4BYTE_ABGR);
		Graphics2D g = img.createGraphics(); 
			//(Graphics2D)img.getGraphics();
		g.setColor(Color.BLACK);
		g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
				RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);

		chip.draw(g);
		ImageIcon icon = new ImageIcon(img);
		return icon;
	}
	
	/**
	 * 
	 * @return the chip which we represent
	 */
	public Chip getChip()
	{
		if (chip instanceof InputBus)
		{
			return new InputBus((InputBus)chip);
		}
		else if (chip instanceof OutputBus)
		{
			return new OutputBus((OutputBus)chip);
		}
		return new Chip(chip);
	}
	
	/**
	 * Tells the workspace to get ready to add our chip on its
	 * next click event.
	 */
	public void processClickEvent()
	{
		workspace.setChip(getChip());
	}
}
